import { PBRShader } from "./js/shaders.js";
const canvas = document.getElementById("renderCanvas"); // Get the canvas element
// 尝试获取 WebGL2 上下文
const gl = canvas.getContext("webgl2");
if (gl) {
  console.log("支持 WebGL 2.0");
} else {
  alert("设备不支持 WebGL 2.0");
}
// const vertexBuffer = new BABYLON.VertexBuffer()
const engine = new BABYLON.Engine(canvas, true); // Generate the BABYLON 3D engine
function showWorldAxis(size, scene) {
  const makeAxis = function (axis, color) {
    const axisMaterial = new BABYLON.StandardMaterial("axisMat", scene);
    axisMaterial.diffuseColor = color;
    axisMaterial.emissiveColor = color;

    const axisLine = BABYLON.MeshBuilder.CreateLines(
      "axis" + axis,
      {
        points: [
          BABYLON.Vector3.Zero(),
          axis === "X"
            ? new BABYLON.Vector3(size, 0, 0)
            : axis === "Y"
            ? new BABYLON.Vector3(0, size, 0)
            : new BABYLON.Vector3(0, 0, size),
        ],
      },
      scene
    );
    axisLine.color = color;
  };

  makeAxis("X", BABYLON.Color3.Red()); // 红色X轴
  makeAxis("Y", BABYLON.Color3.Green()); // 绿色Y轴
  makeAxis("Z", BABYLON.Color3.Blue()); // 蓝色Z轴
}
const createScene = function () {
  // Creates a basic Babylon Scene object
  const scene = new BABYLON.Scene(engine);
  scene.clearColor = new BABYLON.Color4(0, 0, 0, 0); // RGBA 最后一个参数是 alpha
  const camera = new BABYLON.ArcRotateCamera(
    "camera",
    -Math.PI / 2,
    Math.PI / 2.5,
    3,
    new BABYLON.Vector3(0, 0, 0),
    scene
  );
  // camera.upperBetaLimit = Math.PI / 2.1;    // 限制相机上下旋转角度
  // Targets the camera to scene origin
  camera.setTarget(BABYLON.Vector3.Zero());
  // This attaches the camera to the canvas
  camera.attachControl(canvas, true);
  // const sphere = BABYLON.MeshBuilder.CreateSphere(
  //   "sphere",
  //   { diameter: 2, segments: 32 },
  //   scene
  // );
  // sphere.position.y = 30;
  showWorldAxis(5, scene);
  // Move the sphere upward 1/2 its height
  // Creates a light, aiming 0,1,0 - to the sky
  // const light = new BABYLON.HemisphericLight(
  //   "light",
  //   new BABYLON.Vector3(0, 50, 0),
  //   scene
  // );
  // // Dim the light a small amount - 0 to 1
  // light.intensity = 1;
  // 平行光
  const light = new BABYLON.DirectionalLight(
    "light",
    new BABYLON.Vector3(0, -1, 0),
    scene
  );
  light.intensity = 1.0;
  // 环境光
  // const ambientLight = new BABYLON.HemisphericLight(
  //   "hemi",
  //   new BABYLON.Vector3(0, 1, 0),
  //   scene
  // );
  // ambientLight.intensity = 0.3;

  return scene;
};

// 实时移动模型
const startMove = (scene, model) => {
  // let velocity = new BABYLON.Vector3(0, 0, 0); // 每秒前进 1 单位
  const myobserver = new BABYLON.Observable(); // 创建一个可观察者
  setInterval(() => {
    myobserver.notifyObservers((Math.random() - 0.5) * 2 * 10); // 每秒通知观察者
  }, 1000);
  // scene.onBeforeRenderObservable.add(() => {
  //   const deltaTime = engine.getDeltaTime() / 1000;
  //   let nowplace = model.position;
  //   let u = setDamping(nowplace, velocity, deltaTime); // 计算阻尼
  //   model.position = model.position.add(u); // 让该物体相对移动
  // });
  myobserver.add((moveDistance) => {
    let velocity = new BABYLON.Vector3(0, 0, moveDistance);
    // 使用gsap缓动移动
    gsap.to(model.position, {
      duration: 1,
      x: velocity.x,
      y: velocity.y,
      z: velocity.z,
      ease: "power2.inOut",
    });
  });
};

// 加载模型
const loadModel = async function (scene) {
  let model1 = await BABYLON.ImportMeshAsync(
    "./models/scene.gltf",
    // "./models/wrench.gltf",
    // "./models/BoomBox.glb",
    // "./models/model.glb",
    scene
  ).then((result) => {
    // console.log(result);
    let merged;
    //   merged = BABYLON.Mesh.MergeMeshes(
    //   scene.meshes.filter((m) => m.name !== "__root__"),
    //   true,
    //   true,
    //   undefined,
    //   false,
    //   true
    // );
    if (!merged) {
      console.log(result);
      console.warn("合并失败，MergeMeshes 返回 null");
      let mesh = scene.getMeshByName("Frying_Pan_M_Pan_0"); // scene.getMeshByName("_wrench_hi_Volume18");
      if (mesh) {
        const hasTangents = mesh.isVerticesDataPresent(
          BABYLON.VertexBuffer.TangentKind
        );
        // console.log('tangent:', mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
        console.log("是否包含切线:", hasTangents);
      }
      mesh.rotate(BABYLON.Axis.X, Math.PI / 2, BABYLON.Space.LOCAL);
      mesh.position = new BABYLON.Vector3(0, 0, 0);
      mesh.scaling = new BABYLON.Vector3(50, 50, 50);
      // mesh.rotation.x = Math.PI / 2;
      let pbrmat = mesh.material;
      console.log("pbrmat", pbrmat);
      const customMaterial = PBRShader(scene, "myshader");
      // 传递 贴图
      customMaterial.setTexture("albedoTexture", pbrmat.albedoTexture); // 基本颜色
      customMaterial.setTexture("normalTexture", pbrmat.bumpTexture); // 法线贴图
      customMaterial.setTexture(
        "metallicRoughnessTexture",
        pbrmat.metallicTexture
      ); // 金属度和粗糙度贴图
      mesh.material = customMaterial;
    } else {
      merged.name = "MergedModel";
      merged.position = new BABYLON.Vector3(0, 0, 0);
      // merged.scaling = new BABYLON.Vector3(0.1, 0.1, 0.1);
      merged.scaling = new BABYLON.Vector3(100, 100, 100);
      const customMaterial = PBRShader(scene, "customPBR");
      // 传递 贴图
      const texture = new BABYLON.Texture(
        "./textures/Bronze03_1K_BaseColor.png",
        scene,
        false,
        false,
        BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
        () => {
          customMaterial.setTexture("albedoTexture", texture);
        }
      );
      const texture2 = new BABYLON.Texture(
        "./textures/Bronze03_1K_Roughness.png",
        scene,
        false,
        false,
        BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
        () => {
          customMaterial.setTexture("roughnessTexture", texture2);
        }
      );
      const texture3 = new BABYLON.Texture(
        "./textures/Bronze03_1K_Metallic.png",
        scene,
        false,
        false,
        BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
        () => {
          customMaterial.setTexture("metallicTexture", texture3);
        }
      );
      const texture4 = new BABYLON.Texture(
        "./textures/Bronze03_1K_Normal.png",
        scene,
        false,
        false,
        BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
        () => {
          customMaterial.setTexture("normalTexture", texture4);
        }
      );
      merged.material = customMaterial;
    }
    return merged;
  });
  // startMove(scene, model1);
  // startAnimation(model1);
};
const scene = await createScene(); //Call the createScene function
loadModel(scene);
// Register a render loop to repeatedly render the scene
engine.runRenderLoop(function () {
  scene.render();
});
// Watch for browser/canvas resize events
window.addEventListener("resize", function () {
  engine.resize();
});
